package com.thb.pay.manage.web.sys;

import com.thb.pay.api.sys.vo.resp.SysUserVo;
import com.thb.pay.core.annotation.LoginRequired;
import com.thb.pay.core.cache.EhcacheUtils;
import com.thb.pay.core.enums.Action;
import com.thb.pay.core.enums.ExceptionEnum;
import com.thb.pay.core.exception.RRException;
import com.thb.pay.core.utils.Constant;
import com.thb.pay.core.utils.IdWorker;
import com.thb.pay.core.utils.R;
import com.thb.pay.manage.comm.utils.AdminConstants;
import com.thb.pay.manage.service.FeginCommService;
import com.thb.pay.vo.req.LoginReq;
import com.xiaoleilu.hutool.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/sys")
public class LoginController {

    @Autowired
    private FeginCommService feginCommService;

    /**
     * 登录
     */
    @LoginRequired(value = Action.Skip)
    @PostMapping(value = "/auth")
    public R auth(@RequestBody @Valid LoginReq loginReq) {
        Object userErrorCount = EhcacheUtils.getInstance().get(AdminConstants.CACHE_MANAGE_NAME, String.format(AdminConstants.CACHE_MANAGE_USE_ERROR_COUNT_KEY, loginReq.getUsername()));
        if (userErrorCount != null) {
            if (Integer.valueOf(userErrorCount + "") >= AdminConstants.MAX_ERROR_USER_COUNT) {
                throw RRException.build(ExceptionEnum.LOCK_USERNAME);//锁住用户
            }
        }
        SysUserVo sysUserVo = feginCommService.sysUserServiceApi.getByUserName(loginReq.getUsername());
        if (sysUserVo == null) {
            if (log.isDebugEnabled()) {
                log.debug("manage.username:{},is.not.exist.", loginReq.getUsername());
            }
            throw RRException.build(ExceptionEnum.USERNAME_OR_PASSWORD_INCORRECT);
        }
        //验证密码
        boolean isPassword = loginReq.getPassword().equals(sysUserVo.getPassword());
        if (!isPassword) {
            if (log.isDebugEnabled()) {
                log.debug("manage.username:{},password:{},incorrect.{}", loginReq.getUsername(), loginReq.getPassword());
            }
            Integer targetUserErrorCount = userErrorCount == null ? 1 : (Integer.valueOf(userErrorCount + "") + 1);
            EhcacheUtils.getInstance().set(AdminConstants.CACHE_MANAGE_NAME, AdminConstants.CACHE_MANAGE_USE_ERROR_COUNT_KEY, targetUserErrorCount, AdminConstants.CACHE_MANAGE_USER_TIME_KEY);//缓存错误时间
            throw RRException.build(ExceptionEnum.USERNAME_OR_PASSWORD_INCORRECT);
        }

        EhcacheUtils.getInstance().remove(AdminConstants.CACHE_MANAGE_NAME, String.format(AdminConstants.CACHE_MANAGE_USE_ERROR_COUNT_KEY, loginReq.getUsername()));
        String accessToken = IdWorker.get32UUID();
        sysUserVo.setAccessToken(accessToken);
        sysUserVo.setPassword(null);//密码不能泄露
        EhcacheUtils.getInstance().set(String.format(Constant.ACCESS_TOKEN, accessToken), sysUserVo, Constant.EXPIRE_ACCESS_TOKEN_TIME);

        return R.okData(sysUserVo);
    }


    /**
     * 获取验证码
     */
    @LoginRequired(value = Action.Skip)
    @GetMapping(value = "/authCode")
    public void generateAuthCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String randomString = RandomUtil.randomString(5);
        ImageIO.write(null, "JPEG", response.getOutputStream());
    }

}
